<?php

namespace Modules\Order;

use Modules\Order\Entities\BaseOrder as Order;

class Cron
{
	public function handle($schedule)
	{
		$that = $this;
		$schedule->call(function() use ($that) {
			try {
				$that->everyMinute();
			}
			catch (\Throwable $e) {
                \Log::error('order cron任务异常');
                \Log::error($e->getMessage());
            }
		})->everyMinute();

		$schedule->call(function() use ($that) {
			try {
				$that->everyHour();
			}
			catch (\Throwable $e) {
                \Log::error('order cron任务异常');
                \Log::error($e->getMessage());
            }
		})->hourly();
	}

	public function everyMinute()
	{
		// 自动关闭订单
		$orders = Order::status('pay_pending')->whereNotNull('auto_closed_at')->where('auto_closed_at', '<', now())->get();
		foreach ($orders as $order) {
			$order->closeByPayTimeout();
		}

		// 自动完成订单
		$startTime = date('Y-m-d H:i:s', strtotime('-7 days'));
		$orders = Order::status('working')->where('delivered_at', '<', $startTime)->get();
		foreach ($orders as $order) {
			$order->complete();
		}
	}

	public function everyHour()
	{
		// 每个小时结算一下快手的订单
		// 自动关闭订单
		$orders = Order::paid()->where([
			'is_kuaishou_order_completed' => 0,
			['money_paid_at', '<', date('Y-m-d H:i:s', strtotime('-7 days'))],
			'pay_type' => 'kuaishou'
		])->get();

		foreach ($orders as $order) {
			$order->completeForKuaishou();
		}
	}
}